package my.suveng.util.json;

import cn.hutool.core.lang.caller.CallerUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import my.suveng.model.common.interfaces.define.StaticUtil;
import my.suveng.util.log.PlusLogFactoryHutool;

/**
 * jackson工具类
 * @author suwenguang
 **/
@StaticUtil
public class Jackson {
    //hutool日志
    private static final Log log = LogFactory.setCurrentLogFactory(new PlusLogFactoryHutool()).getLog(CallerUtil.getCaller().getName());

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    // 静态内部类
    private static ObjectMapper getObjectMapper() {
        //配置jsonfactory
        JsonFactory factory = OBJECT_MAPPER.getFactory();
        factory.enable(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_COMMENTS);
        factory.enable(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_YAML_COMMENTS);
        //配置javabean序列化配置
        //objectMapper.configure(SerializationFeature.CLOSE_CLOSEABLE,true);
        return OBJECT_MAPPER;
    }

    /**
     * 转json字符串
     * @author suwenguang
     */
    public static String toJsonString(Object o) {
        try {
            return OBJECT_MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error(e);
            return "异常:" + e.getMessage();
        }
    }

    /**
     * json字符串转对象
     * @author suwenguang
     */
    public static <T> T parseJson(String json, Class<T> clazz) {
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error(e);
            return null;
        }
    }


}
